/**
 * 3η ΓΕ 2013-2014 - Super Market
 * ΦΡΑΓΚΟΥΛΟΠΟΥΛΟΥ ΕΜΜΑΝΟΥΕΛΑ (69298)
 * ΧΑΛΔΑΣ ΧΑΡΑΛΑΜΠΟΣ (69305)
 * ΧΟΡΜΟΒΙΤΗΣ ΙΩΑΝΝΗΣ (69325)
 * ΧΟΥΣΤΟΥΛΑΚΗ ΕΥΑΓΓΕΛΙΑ (69327)
 */
package simulation;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

/**
 * Class δημιουργίας XML αρχείου
 */
public class PurchaseXMLManager {

    ///
    public void saveFile(File xmlFile, List<xmlRecord> plist)
            throws ParserConfigurationException,
            TransformerConfigurationException,
            TransformerException,
            SAXException,
            IOException {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc;
        Element rootElement;

        if (xmlFile.exists()) {
            doc = docBuilder.parse(xmlFile);
            NodeList rootList = doc.getElementsByTagName("purchases");
            rootElement = (Element) rootList.item(0);

        } else {
            doc = docBuilder.newDocument();
            rootElement = doc.createElement("purchases");
            doc.appendChild(rootElement);
        }

		//Element rootElement = doc.createElement("purchases");
        //doc.appendChild(rootElement);
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

        for (xmlRecord p : plist) {
            Element purchase = doc.createElement("Purchase");
            Attr attr = doc.createAttribute("id");
            attr.setValue("" + p.getPurchaseId());
            purchase.setAttributeNode(attr);

            Element date = doc.createElement("date");
            date.appendChild(doc.createTextNode(df.format(p.getPurchaseDate())));
            purchase.appendChild(date);

            Element amount = doc.createElement("amount");
            amount.appendChild(doc.createTextNode(p.getAmount() + ""));
            purchase.appendChild(amount);

            Element pointsEarned = doc.createElement("points_earned");
            pointsEarned.appendChild(doc.createTextNode(p.getPoints_earned() + ""));
            purchase.appendChild(pointsEarned);

            Element delivery = doc.createElement("delivery");
            delivery.appendChild(doc.createTextNode(p.isDelivery() + ""));
            purchase.appendChild(delivery);

            Element store = doc.createElement("store");
            store.appendChild(doc.createTextNode(p.getStore()));
            purchase.appendChild(store);

            Element customer = doc.createElement("customer");
            customer.appendChild(doc.createTextNode(p.getCustomer()));
            purchase.appendChild(customer);

            Element retries = doc.createElement("retries");
            retries.appendChild(doc.createTextNode(p.getRetries() + ""));
            purchase.appendChild(retries);
            
            for (retry r:p.getRetriesList()) {
                Element retryInfo = doc.createElement("retry" + r.getIndex());
                retryInfo.appendChild(doc.createTextNode(
                                df.format(r.getTimestamp()) + ", " +
                                r.getThreadName()));
                purchase.appendChild(retryInfo);
            }
            
            Element result = doc.createElement("result");
            result.appendChild(doc.createTextNode(p.getResult() + ""));
            purchase.appendChild(result);
            
            rootElement.appendChild(purchase);
        }

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        DOMSource source = new DOMSource(doc);
        System.out.print("Writing " + xmlFile.getName() + " ... ");
        StreamResult result = new StreamResult(xmlFile);

		// Output to console for testing
        //result = new StreamResult(System.out);
        transformer.transform(source, result);
        System.out.print("done.");
    }

    public float calcAverage(String fname)
            throws SAXException,
            IOException,
            ParserConfigurationException {
        float total = 0;
        int count = 0;

        File xmlFile = new File(fname);
        if (!xmlFile.exists()) {
            return 0;
        }

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("purchases");
        Node root = nList.item(0);
        NodeList plist = root.getChildNodes();

        for (int i = 0; i < plist.getLength(); ++i) {
            Node n = plist.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                NodeList nlist = n.getChildNodes();
                for (int j = 0; j < nlist.getLength(); ++j) {
                    Node n2 = nlist.item(j);
                    if (n2.getNodeType() == Node.ELEMENT_NODE) {
                        if (n2.getNodeName().equals("amount")) {
                            total += Float.parseFloat(n2.getTextContent());
                            ++count;
                        }
                    }
                }
            }
        }
        if (count == 0) {
            return 0;
        }
        return total / count;
    }
}
